package cn.spream.common.util;

import org.apache.commons.io.FilenameUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * 图片处理工具类
 * Created with IntelliJ IDEA.
 * User: shaojiaxin
 * Date: 13-7-22
 * Time: 下午9:16
 * To change this template use File | Settings | File Templates.
 */
public class ImageUtils {

    //支持的图片类型
    private final static Set<String> types = new HashSet<String>();

    static {
        types.add(".gif");
        types.add(".jpg");
        types.add(".jpeg");
        types.add(".bmp");
        types.add(".png");
    }

    /**
     * 判断文件是不是图片
     *
     * @param file
     * @return
     */
    public static boolean isImage(String file) {
        for (String type : types) {
            if (file.toLowerCase().endsWith(type)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 根据图片路径获取图片宽和高
     *
     * @param file
     * @return [宽, 高]
     * @throws IOException
     */
    public static int[] getImageWidthHeight(String file) throws IOException {
        int result[] = {};
        BufferedImage image = null;
        if (file != null && file.length() > 0) {
            if (isImage(file)) {
                image = ImageIO.read(new File(file));
                result[0] = image.getWidth();
                result[1] = image.getHeight();
            }
        }
        return result;
    }

    /**
     * 判断所有的图片后缀是否是相同的
     *
     * @param imgs
     * @return
     */
    public static boolean isSameType(String[] imgs) {
        Set<String> set = new HashSet<String>();
        for (String img : imgs) {
            set.add(FilenameUtils.getExtension(img).toLowerCase());
        }
        return set.size() == 1;
    }

    /**
     * 判断所有的图片后缀是否是相同的
     *
     * @param collection
     * @return
     */
    public static boolean isSameType(Collection<String> collection) {
        Set<String> set = new HashSet<String>();
        for (String img : collection) {
            set.add(FilenameUtils.getExtension(img).toLowerCase());
        }
        return set.size() == 1;
    }

}
